import path from "path";
import request from 'request';
import { cloud } from '@hw-agconnect/cloud-server';
import { user_push_token } from './model/user_push_token'; // location是Server Model
import { PushMessageService } from './PushMessageService'

// const ZONE_NAME = 'HMOSWorld';

const SEND_URL = 'https://api.push.hicloud.com/v3/388421841222001047/messages:send';
// const PRIVATE_KEY = 'private_key';
// const ISS = 'sub_account';
// const KID = 'key_id';

// default是location对象类型使用的存储区名
// 创建链接数据库的句柄
const userPushTokenCollection = cloud.database({ zoneName: 'default' }).collection(user_push_token);

export class PushMessage {
  /**
   * 构建发送通知数据（pushtokens,AuthorizationToken）
   * @returns
   */
  async pushUserMessage(): Promise<string | undefined> {
    let result = undefined;
    const pushTokens: string[] = [];
    try {
      // 查询出所有pushtoken
      const userPushTokens: user_push_token[] = await userPushTokenCollection.query().get();

      if (userPushTokens.length > 0) {

        // TODO: 这里可以构建发送的消息内容
        // get a random resource
        // const randomResource: ResourceResp = await this.getRandomResource();
        // if (!randomResource) {
        //   return result;
        // }

        // 抽离表字段中的pushtoken
        for (let index = 0; index < userPushTokens.length; index++) {
          const element: user_push_token = userPushTokens[index];
          pushTokens.push(element.getPush_token());
        }

        // 获取 AuthorizationToken
        const authorization: string = PushMessageService.getAuthorizationToken();
        //  请求发送推送消息
        for (let i = 0; i < pushTokens.length; i += 10) {
          result = await PushMessageService.sendMessage(pushTokens.slice(i, i + 10), authorization);
        }
      }
      return result;
    } catch (error) {
      console.log(`query user error: ${error}`)
    }
  }
}


/**
 * 发送推送通知
 * @param pushTokens
 * @param authorization
 * @returns
 */
function sendMessage(pushTokens: string[], authorization: string) {

  // 构建header头
  const headers = {
    "push-type": 0,
    "Authorization": authorization
  };
  // 构建请求体数据
  const RequestBodyJsonPostData = {
    "payload": {
      "notification": {
        "category": "MARKETING",
        "title": "普通通知标题",
        "body": "普通通知内容",
        "clickAction": {
          "actionType": 0
        },
        "notifyId": 12345
      }
    },
    "target": {
      "token": pushTokens
    },
    "pushOptions": {
      "testMessage": true,
      "ttl": 86400
    }
  }


  return new Promise((resolve, reject) => {
    // 使用POST方式发送请求
    request.post({
      url: SEND_URL,
      form: JSON.stringify(RequestBodyJsonPostData),
      headers: headers
    }, function (err, httpResponse, body) {
      console.log(`sendMessage request: ${httpResponse.statusMessage}`)
      const result = JSON.parse(body);
      if (httpResponse.statusCode == 200 && (result.code === "80000000" || result.code === "80100000")) {
        console.log(`sendMessage success: ${JSON.stringify(body)}`)
        resolve(result.msg);
      } else {
        reject(err);
      }
    })
  });


}

/**
 * 获取 Authorization
 * @param param1
 * @param param2
 * @returns
 */
function getAuthorizationToken(): string {
  // 依赖：npm i jsonwebtoken
  const jwt = require('jsonwebtoken');
  const fs = require('fs');
  // 加载RSA私钥
  // 实际开发时请从服务账号密钥文件中读取private_key保存在.pem中，参考“基于服务账号生成鉴权令牌中创建服务账号密钥文件。
  // const PRIVATE_KEY =
  //   fs.readFileSync('https://sanjitian-1256310189.cos.ap-chengdu.myqcloud.com/huaweikey/private_key.pem', 'utf8');

  // 添加异常处理
  let PRIVATE_KEY;
  try {
    PRIVATE_KEY = fs.readFileSync(
      path.resolve(__dirname, 'private_key.pem'),
      'utf8'
    );

    // 实际开发时请从服务账号密钥文件中读取sub_account
    const ISS = '113684591';
    // 实际开发时请从服务账号密钥文件中读取key_id
    const KID = 'c3ab09b563ac4bd48c264c0d08c9b981';
    // 实际开发时请将公网地址存储在配置文件或数据库
    const AUD = 'https://oauth-login.cloud.huawei.com/oauth2/v3/token';
    // 自定义Header
    const header = {
      alg: 'PS256', // 建议使用PS256算法
      kid: KID,
      typ: 'JWT'    // 类型为JWT
    };
    // 创建JWT载荷
    const payload = {
      iss: ISS, // 实际开发时请从服务账号密钥文件中读取sub_account
      aud: AUD, // 实际开发时请将公网地址存储在配置文件或数据库
      iat: Math.floor(Date.now() / 1000),
      exp: Math.floor(Date.now() / 1000) + 3600
    };
    // 签署JWT
    const token: string = jwt.sign(payload, PRIVATE_KEY, { algorithm: 'PS256', header: header });
    console.log("Generated JWT:", token);
    return "Bearer " + token;
  } catch (error) {
    console.error('密钥加载失败:', error);
    throw new Error('身份验证配置错误');
  }

}

